package goods

import (
	"context"
	"github.com/gin-gonic/gin"
	"mxshop_api/goods-web/api"
	"mxshop_api/goods-web/forms"
	"mxshop_api/goods-web/global"
	"mxshop_api/goods-web/proto"
	"net/http"
	"strconv"
)

func List(ctx *gin.Context) {

	//商品列表
	//处理筛选条件 最大小价格 ishot isNew isTab  categoryId  分页 关键词
	var request proto.GoodsFilterRequest

	priceMin := ctx.DefaultQuery("pmin", "0")
	priceMinInt, _ := strconv.Atoi(priceMin)
	request.PriceMin = int32(priceMinInt)

	priceMax := ctx.DefaultQuery("pmax", "0")
	priceMaxInt, _ := strconv.Atoi(priceMax)
	request.PriceMax = int32(priceMaxInt)

	isHot := ctx.DefaultQuery("ih", "0")
	if isHot == "1" {
		request.IsHot = true
	}
	isNew := ctx.DefaultQuery("in", "0")
	if isNew == "1" {
		request.IsNew = true
	}

	isTab := ctx.DefaultQuery("it", "0")
	if isTab == "1" {
		request.IsTab = true
	}

	categoryId := ctx.DefaultQuery("c", "0")
	categoryIdInt, _ := strconv.Atoi(categoryId)
	request.TopCategory = int32(categoryIdInt)

	pages := ctx.DefaultQuery("p", "0")
	pagesInt, _ := strconv.Atoi(pages)
	request.Pages = int32(pagesInt)

	perNums := ctx.DefaultQuery("pnum", "0")
	perNumsInt, _ := strconv.Atoi(perNums)
	request.PagePerNums = int32(perNumsInt)

	keywords := ctx.DefaultQuery("q", "")
	request.KeyWords = keywords

	brandId := ctx.DefaultQuery("b", "0")
	brandIdInt, _ := strconv.Atoi(brandId)
	request.Brand = int32(brandIdInt)
	//请求服务获取数据
	response, err := global.SrvConn.GoodsList(context.Background(), &request)
	if err != nil {
		api.HandlerGrpcToHttp(err, ctx)
		return
	}
	//组装数据返回
	var goodsList []interface{}
	for _, value := range response.Data {
		goodsList = append(goodsList, map[string]interface{}{
			"id":          value.Id,
			"name":        value.Name,
			"goods_brief": value.GoodsBrief,
			"desc":        value.GoodsDesc,
			"ship_free":   value.ShipFree,
			"images":      value.Images,
			"desc_images": value.DescImages,
			"front_image": value.GoodsFrontImage,
			"shop_price":  value.ShopPrice,
			"category": map[string]interface{}{
				"id":   value.Category.Id,
				"name": value.Category.Name,
			},
			"brand": map[string]interface{}{
				"id":   value.Brand.Id,
				"name": value.Brand.Name,
				"logo": value.Brand.Logo,
			},
			"is_hot":  value.IsHot,
			"is_new":  value.IsNew,
			"on_sale": value.OnSale,
		})
	}

	ctx.JSON(http.StatusOK, gin.H{
		"data":  goodsList,
		"total": response.Total,
	})
}

func New(ctx *gin.Context) {

	//参数验证
	var goodsForm forms.GoodsForm
	if err := ctx.ShouldBind(&goodsForm); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	goodsInfoResponse, err := global.SrvConn.CreateGoods(context.Background(), &proto.CreateGoodsInfo{
		Name:            goodsForm.Name,
		GoodsSn:         goodsForm.GoodsSn,
		Stocks:          goodsForm.Stocks,
		MarketPrice:     goodsForm.MarketPrice,
		ShopPrice:       goodsForm.ShopPrice,
		GoodsBrief:      goodsForm.GoodsBrief,
		ShipFree:        goodsForm.ShipFree,
		Images:          goodsForm.Images,
		DescImages:      goodsForm.DescImages,
		GoodsFrontImage: goodsForm.FrontImage,
		CategoryId:      goodsForm.CategoryId,
		BrandId:         goodsForm.Brand,
	})
	if err != nil {
		api.HandlerGrpcToHttp(err, ctx)
		return
	}
	//todo 库存设置

	ctx.JSON(http.StatusOK, goodsInfoResponse)
}

func Detail(ctx *gin.Context) {

	goodsDetailForm := forms.GoodsDetailForm{}
	err := ctx.ShouldBindUri(&goodsDetailForm)
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	//请求服务获取数据
	detail, err := global.SrvConn.GetGoodsDetail(context.Background(), &proto.GoodInfoRequest{Id: goodsDetailForm.ID})
	if err != nil {
		api.HandlerGrpcToHttp(err, ctx)
		return
	}
	//组装数据返回 map类型
	data := map[string]interface{}{
		"id":          detail.Id,
		"name":        detail.Name,
		"goods_brief": detail.GoodsBrief,
		"desc":        detail.GoodsDesc,
		"ship_free":   detail.ShipFree,
		"images":      detail.Images,
		"desc_images": detail.DescImages,
		"front_image": detail.GoodsFrontImage,
		"shop_price":  detail.ShopPrice,
		"category": map[string]interface{}{
			"id":   detail.Category.Id,
			"name": detail.Category.Name,
		},
		"brand": map[string]interface{}{
			"id":   detail.Brand.Id,
			"name": detail.Brand.Name,
			"logo": detail.Brand.Logo,
		},
		"is_hot":  detail.IsHot,
		"is_new":  detail.IsNew,
		"on_sale": detail.OnSale,
	}
	ctx.JSON(http.StatusOK, data)
}

func Delete(ctx *gin.Context) {

	//获取参数
	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	//调用方法
	_, err = global.SrvConn.DeleteGoods(context.Background(), &proto.DeleteGoodsInfo{Id: int32(idInt)})
	//返回数据
	if err != nil {
		api.HandlerGrpcToHttp(err, ctx)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "删除成功",
	})
}

func Stocks(ctx *gin.Context) {

	id := ctx.Param("id")
	_, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	return
}

func UpdateStatus(ctx *gin.Context) {

	//获取参数
	var goodsStatusForm forms.GoodsStatusForm
	if err := ctx.ShouldBind(&goodsStatusForm); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	//调用方法
	_, err = global.SrvConn.UpdateGoods(context.Background(), &proto.CreateGoodsInfo{
		IsNew:  goodsStatusForm.IsNew,
		IsHot:  goodsStatusForm.IsHot,
		OnSale: goodsStatusForm.OnSale,
		Id:     int32(idInt),
	})
	if err != nil {
		api.HandlerGrpcToHttp(err, ctx)
		return
	}
	//返回结果
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "修改成功",
	})
}

func Update(ctx *gin.Context) {

	//获取参数
	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	var goodsForm forms.GoodsForm
	if err = ctx.ShouldBind(&goodsForm); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	//调用方法
	_, err = global.SrvConn.UpdateGoods(context.Background(), &proto.CreateGoodsInfo{
		Id:              int32(idInt),
		Name:            goodsForm.Name,
		GoodsSn:         goodsForm.GoodsSn,
		Stocks:          goodsForm.Stocks,
		MarketPrice:     goodsForm.MarketPrice,
		ShopPrice:       goodsForm.ShopPrice,
		GoodsBrief:      goodsForm.GoodsBrief,
		ShipFree:        goodsForm.ShipFree,
		Images:          goodsForm.Images,
		DescImages:      goodsForm.DescImages,
		GoodsFrontImage: goodsForm.FrontImage,
		CategoryId:      goodsForm.CategoryId,
		BrandId:         goodsForm.Brand,
	})
	if err != nil {
		api.HandlerGrpcToHttp(err, ctx)
		return
	}
	//返回结果
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "修改成功",
	})
}
